package net.expectx.micro.shop.api.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;

import net.expectx.common.single.base.BaseResultConstants;
import net.expectx.micro.shop.api.common.ApiConstants;
import net.expectx.micro.shop.api.common.ApiResult;
import net.expectx.micro.shop.api.common.ApiResultConstants;
import net.expectx.micro.shop.api.common.util.ApiUtils;
import net.expectx.micro.shop.api.validator.NotNullValidator;
import net.expectx.micro.shop.dao.bean.*;
import net.expectx.micro.shop.rpc.api.ProductProductService;
import net.expectx.micro.shop.rpc.api.SystemRegionService;
import net.expectx.micro.shop.rpc.api.SystemSettingService;
import net.expectx.micro.shop.rpc.api.SystemTypeGroupService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lijian
 */
@Api(tags = "公共", description = "工具类相关接口")
@Controller
@RequestMapping("util")

public class UtilController {

    @Autowired
    private SystemSettingService systemSettingService;
    @Autowired
    private SystemTypeGroupService systemTypeGroupService;
    @Autowired
    private SystemRegionService systemRegionService;
    @ApiOperation(value = "获取系统信息(不需)")
    @ApiImplicitParams({
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @RequestMapping(value = "/systemInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<ApiResult> systemInfo() throws Exception {
        SystemSettingExample systemSettingExample=new SystemSettingExample();
        systemSettingExample.createCriteria().andIsDeletedEqualTo(ApiConstants.NO);
        List<SystemSetting> systemSettings = systemSettingService.selectByExample(systemSettingExample);
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE,ApiResultConstants.SUCCESS, systemSettings), HttpStatus.OK);
    }

    @ApiOperation("根据字典值加载字典数据项(不需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeGroupCodes", value = "字典标识", defaultValue = "", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 501, message = "参数检查失败"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @GetMapping("loadTypeItems")
    public ResponseEntity<ApiResult> loadTypeItems(String typeGroupCodes, HttpServletRequest request) throws Exception {
        FluentValidator fluentValidator = FluentValidator.checkAll();
        if (!Strings.isNullOrEmpty(typeGroupCodes)) {
            fluentValidator.on(typeGroupCodes, new NotNullValidator("字典组编号集合"));
        }
        ComplexResult result = fluentValidator.doValidate().result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ResponseEntity<>(new ApiResult(false, ApiResultConstants.PARAM_CHECK_FAILED, result.getErrors()), HttpStatus.OK);
        }
        Map map = Maps.newHashMapWithExpectedSize(7);
        List<String> typeGroupCode=new ArrayList<>();
        for (Integer i = 0; i < typeGroupCodes.split(",").length; i++) {
            typeGroupCode.add( typeGroupCodes.split(",")[i]);
        }
        SystemTypeGroupExample systemTypeGroupExample=new SystemTypeGroupExample();

        systemTypeGroupExample.createCriteria().andTypeGroupCodeIn(typeGroupCode);
        List<SystemTypeGroup> systemTypeGroups = systemTypeGroupService.selectByExample(systemTypeGroupExample);
        if (systemTypeGroups.isEmpty()) {
            systemTypeGroupExample=new SystemTypeGroupExample();

            systemTypeGroups = systemTypeGroupService.selectByExample(systemTypeGroupExample);
            StringBuffer sb = new StringBuffer();
            for (SystemTypeGroup systemTypeGroup : systemTypeGroups) {
                sb.append(systemTypeGroup.getTypeGroupCode() + " ");
            }
            map.put("typeGroupCodes", "只接受参数为[" + sb + "]");
            return new ResponseEntity<>(new ApiResult(false,ApiResultConstants.FAILED, map), HttpStatus.OK);
        } else {
            List<SystemTypeGroup> tempSystemTypeGroups;
            for (SystemTypeGroup systemTypeGroup : systemTypeGroups) {
                if (map.containsKey(systemTypeGroup.getTypeGroupCode())) {
                    tempSystemTypeGroups = (List<SystemTypeGroup>) map.get(systemTypeGroup.getTypeGroupCode());
                    for (SystemType systemType : systemTypeGroup.getSystemTypes()) {
                        systemType.setTypeName(systemType.getTypeName());
                    }
                    tempSystemTypeGroups.add(systemTypeGroup);
                    map.put(systemTypeGroup.getTypeGroupCode(), tempSystemTypeGroups);
                } else {
                    tempSystemTypeGroups = new ArrayList<>();
                    for (SystemType systemType : systemTypeGroup.getSystemTypes()) {
                        systemType.setTypeName(systemType.getTypeName());
                    }
                    tempSystemTypeGroups.add(systemTypeGroup);
                    map.put(systemTypeGroup.getTypeGroupCode(), tempSystemTypeGroups);
                }
            }
            return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, map), HttpStatus.OK);
        }

    }

    @ApiOperation(value = "数据库地址获取(不需)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "地区ID", defaultValue = "100000", required = true, dataType = "Integer", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "失败"),
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 500, message = "系统异常"),
            @ApiResponse(code = 504, message = "缺少消息头MAC地址或为空"),
            @ApiResponse(code = 505, message = "缺少消息头User-Agent地址或为空"),
            @ApiResponse(code = 506, message = "缺少消息头App-Key和App-Secret参数或为空"),
            @ApiResponse(code = 506001, message = "无效的App-Key"),
            @ApiResponse(code = 506002, message = "无效的App-Secret"),
    })
    @RequestMapping(value = "/region", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<ApiResult> region(Long id) throws Exception {
        List<Map> list = new ArrayList<>();
        if (StringUtils.isEmpty(id.toString())) {
            id = 100000L;
        }
        SystemRegionExample systemRegionExample=new SystemRegionExample();
        systemRegionExample.createCriteria().andPidEqualTo(id);
        systemRegionExample.setOrderByClause("first_letter asc");
        List<SystemRegion> regions = systemRegionService.selectByExample(systemRegionExample);
        for (SystemRegion region : regions) {
            Map map = Maps.newHashMapWithExpectedSize(7);
            map.put("id", region.getId());
            map.put("pId", region.getPid());
            map.put("name", region.getName());
            systemRegionExample=new SystemRegionExample();
            systemRegionExample.createCriteria().andPidEqualTo(region.getId());
            systemRegionExample.setOrderByClause("first_letter asc");
            if (systemRegionService.countByExample(systemRegionExample)==0) {
                map.put("isParent", false);
            } else {
                map.put("isParent", true);
            }
            list.add(map);
        }
        return new ResponseEntity<>(new ApiResult(Boolean.TRUE, ApiResultConstants.SUCCESS, list), HttpStatus.OK);
    }

}
